package Skill

import (
	codecs "sanguo/codec/cs"
	"sanguo/node/common/attr"
	"sanguo/node/common/transaction"
	"sanguo/node/node_game"
	"sanguo/node/node_game/module/role"
	"sanguo/node/node_game/user"
	cs_message "sanguo/protocol/cs/message"
	"time"

	"github.com/golang/protobuf/proto"
)

type transactionResetSkillPoint struct {
	transaction.TransactionBase
	user    *user.User
	req     *codecs.Message
	resp    *cs_message.ResetSkillPointToC
	errcode cs_message.EnumType
}

func (this *transactionResetSkillPoint) GetModuleName() string {
	return "Skill"
}

func (this *transactionResetSkillPoint) GetReplyMsg() proto.Message {
	return &cs_message.ResetSkillPointToC{}
}

func (this *transactionResetSkillPoint) SetExpiredTime(expired time.Time) {
	this.Expired = expired
}

func (this *transactionResetSkillPoint) GetExpiredTime() time.Time {
	return this.Expired
}

func (this *transactionResetSkillPoint) Begin() {

	this.resp = &cs_message.ResetSkillPointToC{}
	msg := this.req.GetData().(*cs_message.ResetSkillPointToS)
	roleModule := this.user.GetModuleByName("role").(*role.RoleModule)
	role := roleModule.CurrentRole()

	if nil == role || !role.IsRoleModleData() {
		node_game.Infoln(this.user.GetUserID(), "ResetSkillPoint fail : no select role")
		this.errcode = cs_message.EnumType_ERROR
		this.user.EndTrans(this)
		return
	}
	node_game.Infof("%s %d Call ResetSkillPoint type:%d ", role.GetUserID(), role.GetID(), msg.GetSkillType())

	roleSkill := role.GetRoleSkill().GetRoleSkill(msg.GetSkillType())
	if roleSkill == nil {
		this.errcode = cs_message.EnumType_ERROR
		this.user.EndTrans(this)
		return
	}

	diamond, _ := role.GetRoleAttr().GetAttr(attr.Diamond)
	resetPoint := roleSkill.TotalSkillPoint - roleSkill.CurrentSkillPoint
	diamond -= int64(resetPoint) * 2
	if diamond < 0 {
		this.errcode = cs_message.EnumType_ERROR
		this.user.EndTrans(this)
		return
	}

	role.GetRoleSkill().ResetSkillPoint(msg.GetSkillType())
	role.OnSkillDirty()

	node_game.Infoln(role.GetUserID(), role.GetID(), "Reset SkillPoint OK")
	this.errcode = cs_message.EnumType_OK
	this.user.EndTrans(this)
}

func (this *transactionResetSkillPoint) End() {
	this.resp.Errcode = cs_message.EnumType(this.errcode).Enum()
	this.user.Reply(this.req.GetSeriNo(), this.resp)
}

func (this *transactionResetSkillPoint) Timeout() {
	this.resp.Errcode = cs_message.EnumType(cs_message.EnumType_RETRY).Enum()
	this.user.EndTrans(this)
}

func init() {
	user.RegisterTransFunc(&cs_message.ResetSkillPointToS{}, func(user *user.User, msg *codecs.Message) transaction.Transaction {
		return &transactionResetSkillPoint{
			user: user,
			req:  msg,
		}
	})
}
